package com.qys.training.biz.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加解密工具类
 *
 * @author Winstone
 * @date 2020/8/4 - 1:03 下午
 */
public class CypherUtil {
    /**
     * 通过MD5的方式对明文进行加密
     *
     * @param plainText 明文
     * @return cipherText 密文
     */
    public static String encoderByMd5(String plainText) {
        String cipherText = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            cipherText = new String(md5.digest(plainText.getBytes("utf-8")), "utf-8");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return cipherText;
    }

    /**
     * 验证明文 是否 是MD5 加密的密文
     *
     * @param plainText  明文
     * @param cipherText 密文
     * @return Boolean
     */
    public static Boolean verifyEncryption(String plainText, String cipherText) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            String cipherTextByMD5 = new String(md5.digest(plainText.getBytes("utf-8")), "utf-8");
            if (cipherTextByMD5.equals(cipherText)) {
                return true;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }

}
